/* 
	Copyright (c) 2007, Cliff Rowley, James Deakin
	All rights reserved.
	
	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are
	met:
	
	    * Redistributions of source code must retain the above copyright
	      notice, this list of conditions and the following disclaimer.
	    * Redistributions in binary form must reproduce the above copyright
	      notice, this list of conditions and the following disclaimer in
	      the documentation and/or other materials provided with the
	      distribution.
	    * Neither the name of the <ORGANIZATION> nor the names of its
	      contributors may be used to endorse or promote products derived
	      from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
	A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
	OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
	DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
	THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
	OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package acid.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
 * Acid layout generator Ant task.
 * @author cliff <cliffrowley@gmail.com>
 */
public class Generate extends Task {
	
	/** The source directory */
	private String srcdir;
	/** The output directory */
	private String destdir;
	/** The template filename */
	private String template;
	
	/** The source directory file */
	private File srcdirf;
	/** The output directory file */
	private File destdirf;
	
	/** The template file source */
	private Source tsrc;
	
	private Transformer trans;

	public void execute() throws BuildException {
		if (srcdir == null || srcdir.length() == 0) {
			throw new BuildException("Argument 'srcdir' missing or invalid");
		}
		if (destdir == null || destdir.length() == 0) {
			throw new BuildException("Argument 'destdir' missing or invalid");
		}
		if (template == null || template.length() == 0) {
			throw new BuildException("Argument 'template' missing or invalid");
		}
		
		try {
			ArrayList<SourceFile> sources = new ArrayList<SourceFile>();
			
			tsrc = new StreamSource(new FileInputStream(new File(template)));
			
			TransformerFactory tf = TransformerFactory.newInstance();
			trans = tf.newTransformer(tsrc);
			
			trans.setOutputProperty("method", "text");
			
			srcdirf  = new File(srcdir);
			destdirf = new File(destdir);
			
			if (srcdirf.isDirectory()) {
				sources.addAll(enumerate(srcdirf));
				
				System.out.println("Generating " + sources.size() + " file(s)");
				
				for (int i = 0; i < sources.size(); i++) {
					SourceFile sf = sources.get(i);
					generate(sf);
				}
			}
			else {
				throw new BuildException("Source directory is not a directory!");
			}
		}
		
		catch (Exception e) {
			e.printStackTrace();
			throw new BuildException(e);
		}
	}
	
	/**
	 * Recursively enumerate XML files in a given directory.
	 * @param dir The directory to enumerate.
	 * @return A list of XML files.
	 * @throws Exception
	 */
	private ArrayList<SourceFile> enumerate(File dir) throws Exception {
		ArrayList<SourceFile> sources = new ArrayList<SourceFile>();
		
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory() && files[i].getName() != "." && files[i].getName() != "..") {
				sources.addAll(enumerate(files[i]));
			}
			else {
				File file = files[i];
				String path = file.getPath();
				
				/* Match .XML */
				if (path.toLowerCase().matches(".*\\.xml$")) {
					/* Build package name */
					StringBuffer pkg = new StringBuffer();
					File parent = file.getParentFile();
					while (parent != null) {
						if (parent.equals(srcdirf) == false) {
							if (pkg.length() > 0) {
								pkg.insert(0, ".");
							}
							pkg.insert(0, parent.getName());
						}
						else {
							break;
						}
						parent = parent.getParentFile();
					}
					
					/* Determine class name */
					String fname = file.getName();
					int idx = fname.lastIndexOf('.');
					String classname = fname.substring(0, idx);
					
					/* Generate output file name */
					String outpath = pkg.toString().replace(".", File.separator);
					File outfile = new File(
						new StringBuffer()
						.append(destdirf.getAbsolutePath())
						.append(File.separator)
						.append(outpath)
						.append(File.separator)
						.append(classname)
						.append(".as")
						.toString()
					);
					
					/* Add source file to list */
					SourceFile sf = new SourceFile(file, outfile, pkg.toString(), classname);
					sources.add(sf);
				}
			}
		}
		
		return sources;
	}
	
	/**
	 * Generate an AS file from an XML source file.
	 * @param sf The source file.
	 * @throws Exception
	 */
	private void generate(SourceFile sf) throws Exception {
		System.out.println("Processing " + sf.srcfile.getPath());
		
		File parent = sf.destfile.getParentFile();
		parent.mkdirs();
		
		Source isrc = new StreamSource(new FileInputStream(sf.srcfile));
		Result res  = new StreamResult(new FileOutputStream(sf.destfile));
		
		trans.setParameter("filename",    sf.destfile.getName());
		trans.setParameter("classname",   sf.classname);
		trans.setParameter("package",     sf.pkg);
		trans.setParameter("fqclassname", sf.pkg + "." + sf.classname);
		
		trans.transform(isrc, res);
	}
	
	public void setSrcdir(String srcdir) {
		this.srcdir = srcdir;
	}
	
	public void setDestdir(String destdir) {
		this.destdir = destdir;
	}
	
	public void setTemplate(String template) {
		this.template = template;
	}
	
}
